using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;

namespace CustomControls
{
    public partial class CustomGrid : DevExpress.XtraEditors.XtraUserControl
    {
        public delegate void OnInvalidValueException(object sender, DevExpress.XtraEditors.Controls.InvalidValueExceptionEventArgs e);
        public event OnInvalidValueException InvalidValueException;

        #region HtDataForGrid property
        private Hashtable _HtDataForGrid = new Hashtable();
        public Hashtable HtDataForGrid
        {
            get
            {
                return _HtDataForGrid;
            }
            set
            {
                _HtDataForGrid = value;
            }
        }
        #endregion

        #region OptionsBehavior property
        public GridOptionsBehavior OptionsBehavior
        {
            get
            {
                return gridViewKhoanMuc.OptionsBehavior;
            }
        }
        #endregion

        #region DataSource property
        public object DataSource
        {
            get
            {
                return gridControlKhoanMuc.DataSource;
            }
            set
            {
                gridControlKhoanMuc.DataSource = value;
            }
        }
        #endregion

        public CustomGrid()
        {
            InitializeComponent();
        }
        private void CustomGrid_Load(object sender, EventArgs e)
        {
            rItemPopupContainerEditTaiKhoan1.Tag = "TaiKhoan1ID";
            rItemPopupContainerEditTaiKhoan2.Tag = "TaiKhoan2ID";
            rItemPopupContainerEditTaiKhoan3.Tag = "TaiKhoan3ID";
            rItemPopupContainerEditTaiKhoan4.Tag = "TaiKhoan4ID";
            rItemPopupContainerEditTaiKhoan5.Tag = "TaiKhoan5ID";

            rItemPopupContainerEditStore1.Tag = "Store1ID";
            rItemPopupContainerEditThueSuat1.Tag = "ThueSuat1ID";
            rItemPopupContainerEditKho1.Tag = "Kho1ID";
            rItemPopupContainerEditVuViec1.Tag = "VuViec1ID";
            rItemPopupContainerEditYeuToChiPhi1.Tag = "YeuToChiPhi1ID";
        }

        public void FormatColumns(DataView dv)
        {
            foreach (DevExpress.XtraGrid.Columns.GridColumn gridColumn in gridViewKhoanMuc.Columns)
            {
                switch (gridColumn.Name)
                {
                    case "colTaiKhoan1ID":
                        gridColumn.ColumnEdit = rItemPopupContainerEditTaiKhoan1;
                        break;
                    case "colTaiKhoan2ID":
                        gridColumn.ColumnEdit = rItemPopupContainerEditTaiKhoan2;
                        break;
                    case "colTaiKhoan3ID":
                        gridColumn.ColumnEdit = rItemPopupContainerEditTaiKhoan3;
                        break;
                    case "colTaiKhoan4ID":
                        gridColumn.ColumnEdit = rItemPopupContainerEditTaiKhoan4;
                        break;
                    case "colTaiKhoan5ID":
                        gridColumn.ColumnEdit = rItemPopupContainerEditTaiKhoan5;
                        break;
                    case "colThueSuat1ID":
                        gridColumn.ColumnEdit = rItemPopupContainerEditThueSuat1;
                        break;
                    case "colKho1ID":
                        gridColumn.ColumnEdit = rItemPopupContainerEditKho1;
                        break;
                    case "colVuViec1ID":
                        gridColumn.ColumnEdit = rItemPopupContainerEditVuViec1;
                        break;
                    case "colYeuToChiPhi1ID":
                        gridColumn.ColumnEdit = rItemPopupContainerEditYeuToChiPhi1;
                        break;
                    case "colStore1ID":
                        gridColumn.ColumnEdit = rItemPopupContainerEditStore1;
                        break;
                }
            }

            foreach (DataRowView row in dv)
            {
                string columnName = (string)row["Column Name"];
                gridViewKhoanMuc.Columns[columnName].Visible = (bool)row["HienThi"];
                if ((bool)row["HienThi"])
                {
                    gridViewKhoanMuc.Columns[columnName].VisibleIndex = (int)row["ThuTuHienThi"];
                    gridViewKhoanMuc.Columns[columnName].Caption = (string)row["TenHienThi"];
                    gridViewKhoanMuc.Columns[columnName].ToolTip = (string)row["ToolTip"];
                    gridViewKhoanMuc.Columns[columnName].Width = (int)row["DoRong"];// gridViewKhoanMuc.Columns[columnName].GetBestWidth();
                    if ((bool)row["BatBuocNhap"])
                        gridViewKhoanMuc.Columns[columnName].AppearanceHeader.ForeColor = Color.Crimson;
                }
            }
            foreach (DataRowView row in dv)
            {
                if ((bool)row["HienThi"])
                {
                    string columnName = (string)row["Column Name"];
                    gridViewKhoanMuc.Columns[columnName].VisibleIndex = (int)row["ThuTuHienThi"];
                }
            }
            foreach (DataRowView row in dv)
            {
                if ((bool)row["HienThi"])
                {
                    string columnName = (string)row["Column Name"];
                    gridViewKhoanMuc.Columns[columnName].VisibleIndex = (int)row["ThuTuHienThi"];
                }
            }
        }

        private DataForGrid GetDataForGrid(PopupContainerEdit popupContainerEdit)
        {
            RepositoryItemPopupContainerEdit rep = popupContainerEdit.Properties;
            DataForGrid data = _HtDataForGrid[rep.Tag] as DataForGrid;
            return data;
        }
        private DataForGrid GetDataForGrid(RepositoryItemPopupContainerEdit repositoryItemPopupContainerEdit)
        {
            return _HtDataForGrid[repositoryItemPopupContainerEdit.Tag] as DataForGrid;
        }
        private void FilterRowsInGrid(DataForGrid dataForGrid, string textToFind)
        {
            if (dataForGrid != null)
            {
                if (textToFind != "")
                {
                    string query = "";
                    foreach (string fieldName in dataForGrid.VisibleColumns.Keys)
                    {
                        try
                        {
                            if (dataForGrid.DataSource.Table.Columns[fieldName].DataType == typeof(System.String))
                            {
                                query += string.Format("{0} LIKE '%{1}%' OR ", fieldName, textToFind.Replace("'", "''"));
                            }
                            else if (dataForGrid.DataSource.Table.Columns[fieldName].DataType.ToString().ToLower().IndexOf("int") >= 0)
                            {
                                query += string.Format("{0} = {1} OR ", fieldName, textToFind.Replace("'", "''"));
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                    if (query.EndsWith(" OR ")) query = query.Substring(0, query.Length - 4);
                    else query = "1 = 1";
                    gridControlRef.DataSource = new DataView(dataForGrid.DataSource.ToTable(), query, "", DataViewRowState.CurrentRows);
                }
                else {
                    gridControlRef.DataSource = dataForGrid.DataSource;
                }
            }
        }
        private void ChooseItemToEditor()
        {
            Object oldEditingValue = gridViewKhoanMuc.EditingValue;
            try
            {
                if (gridViewRef.GetSelectedRows().Length == 1)
                {
                    if (gridViewKhoanMuc.ActiveEditor == null) gridViewKhoanMuc.ShowEditor();
                    else 
                    {
                        PopupContainerEdit popupContainerEdit = gridViewKhoanMuc.ActiveEditor as DevExpress.XtraEditors.PopupContainerEdit;

                        int selectedIndex = gridViewRef.GetSelectedRows()[0];
                        DataRowView selectedRow = (gridControlRef.DataSource as DataView)[selectedIndex] as DataRowView;
                        object x = selectedRow[GetDataForGrid(popupContainerEdit).ValueColumn];
                        
                        gridViewKhoanMuc.EditingValue = x;
                        if (popupContainerEdit.IsPopupOpen) popupContainerEdit.ClosePopup();
                    }
                }
            }
            catch (Exception ex)
            {
                gridViewKhoanMuc.EditingValue = oldEditingValue;
            }
        }

        private void gridControlRef_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    ChooseItemToEditor();
                    if (gridViewKhoanMuc.ActiveEditor != null)
                    {
                        gridViewKhoanMuc.ActiveEditor.Focus();
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        private void gridControlRef_MouseUp(object sender, MouseEventArgs e)
        {
            try
            {
                if (this.gridViewRef.FocusedRowHandle >= 0)
                {
                    ChooseItemToEditor();
                }
            }
            catch (Exception ex)
            { 
            }            
        }
        private void gridControlRef_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (gridViewKhoanMuc.ActiveEditor != null)
            {
                gridViewKhoanMuc.ActiveEditor.SendKey(sender, e);
                gridViewKhoanMuc.ActiveEditor.Focus();
            }
        }

        private void repositoryItemPopupContainerEdit_QueryDisplayText(object sender, DevExpress.XtraEditors.Controls.QueryDisplayTextEventArgs e)
        {
            try
            {
                if (e.EditValue is int)
                {
                    DataForGrid data = null;
                    if (sender is RepositoryItemPopupContainerEdit)
                    {
                        data = GetDataForGrid(sender as RepositoryItemPopupContainerEdit);
                    }
                    else if (sender is PopupContainerEdit)
                    {
                        data = GetDataForGrid(sender as PopupContainerEdit);
                    }

                    string query = string.Format("{0} = {1}", data.ValueColumn, e.EditValue);
                    DataRow[] row = (data.DataSource as DataView).Table.Select(query);

                    if (row.Length > 0)
                    {
                        e.DisplayText = row[0][data.DisplayColumn].ToString();
                    }
                    //else
                    //    e.DisplayText = "";
                }
                else
                {
                   // e.DisplayText = "";
                }
            }
            catch (Exception ex)
            {
               // e.DisplayText = "";
            }
        }
        private void repositoryItemPopupContainerEdit_QueryPopUp(object sender, CancelEventArgs e)
        {
            try
            {
                DevExpress.XtraEditors.PopupContainerEdit popupContainerEdit = (sender as DevExpress.XtraEditors.PopupContainerEdit);
                RepositoryItemPopupContainerEdit rep = popupContainerEdit.Properties;

                DataForGrid dataForGrid = _HtDataForGrid[rep.Tag as string] as DataForGrid;
                gridControlRef.DataSource = dataForGrid.DataSource;

                this.gridViewRef.Columns.Clear();
                foreach (string columnName in dataForGrid.VisibleColumns.Keys)
                {
                    this.gridViewRef.Columns.AddVisible(columnName, dataForGrid.VisibleColumns[columnName] as string);
                }
                rep.PopupControl = popupContainerControlRef;
            }
            catch (Exception ex)
            { 
            }
        }
        private void repositoryItemPopupContainerEdit_KeyUp(object sender, KeyEventArgs e)//enter thi chon item
        {
            if (e.KeyCode == Keys.Enter)
            {
                ChooseItemToEditor();
                gridViewKhoanMuc.Focus();
            }
            else if (e.KeyCode == Keys.Down)
            {
                PopupContainerEdit popupContainerEdit = (sender as DevExpress.XtraEditors.PopupContainerEdit);
                if (popupContainerEdit.IsPopupOpen)
                {
                    gridControlRef.Focus();
                }
            }
        }
        private void repositoryItemPopupContainerEdit_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                PopupContainerEdit popupContainerEdit = (sender as DevExpress.XtraEditors.PopupContainerEdit);
                if(!popupContainerEdit.IsPopupOpen)
                    popupContainerEdit.ShowPopup();
                FilterRowsInGrid(GetDataForGrid(popupContainerEdit), popupContainerEdit.Text);
            }
            catch (Exception ex)
            {
            }
        }

        private void gridViewKhoanMuc_InvalidValueException(object sender, DevExpress.XtraEditors.Controls.InvalidValueExceptionEventArgs e)
        {
            if (InvalidValueException != null)
                InvalidValueException(sender, e);
        }

        private void gridControlKhoanMuc_KeyUp(object sender, KeyEventArgs e)
        {
            try {
                if (e.KeyCode == Keys.Delete && gridViewKhoanMuc.SelectedRowsCount >= 1 && this.OptionsBehavior.Editable)
                {
                    if (gridControlKhoanMuc.DataSource is DataTable)
                    {
                        (gridControlKhoanMuc.DataSource as DataTable).Rows.RemoveAt(gridViewKhoanMuc.GetSelectedRows()[0]);
                    }
                }
            }
            catch (Exception ex)
            { 
            }
        }
    }

    public class DataForGrid
    {
        #region VisibleColumns property
        private Hashtable _VisibleColumns = new Hashtable();
        public Hashtable VisibleColumns
        {
            get
            {
                return _VisibleColumns;
            }
            set
            {
                _VisibleColumns = value;
            }
        }
        #endregion

        #region ValueColumn property
        private string _ValueColumn;
        public string ValueColumn
        {
            get
            {
                return _ValueColumn;
            }
            set
            {
                _ValueColumn = value;
            }
        }
        #endregion

        #region DisplayColumn property
        private string _DisplayColumn;
        public string DisplayColumn
        {
            get
            {
                return _DisplayColumn;
            }
            set
            {
                _DisplayColumn = value;
            }
        }
        #endregion

        #region SortColumn property
        private string _SortColumn = "";
        public string SortColumn
        {
            get
            {
                return _SortColumn;
            }
            set
            {
                _SortColumn = value;
            }
        }
        #endregion

        #region DataSource property
        private DataView _DataSource;
        public DataView DataSource
        {
            get
            {
                return _DataSource;
            }
            set
            {
                _DataSource = value;


            }
        }
        #endregion

        #region EditValue property
        private object _EditValue;
        public object EditValue
        {
            get
            {
                return _EditValue;
            }
            set
            {
                _EditValue = value;
            }
        }
        #endregion
    }
}
